package com.springloadfactory;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.util.List;

/**
 * @author fanxiao  2022/2/25
 * @since 1.0.0
 */
@Slf4j
public class LoadFactoryBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		List<Eoo> eoos = SpringFactoriesLoader.loadFactories(Eoo.class, getClass().getClassLoader());
		if (CollUtil.isNotEmpty(eoos)){
		  for (Eoo eoo : eoos) {
			  GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
			  Class<? extends Eoo> eooClass = eoo.getClass();
			  beanDefinition.setBeanClass(eooClass);
			  String beanName = AnnotationBeanNameGenerator.INSTANCE.generateBeanName(beanDefinition, registry);
			  log.info("beanName:{}", beanName);
			  registry.registerBeanDefinition(beanName, beanDefinition);
		  }
		}

	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		log.info("---");
	}
}